<?php
class settingModel extends baseModel{

	//保存配置
	public function save($array) {
        if (empty($array) || !is_array($array)) {
            return false;
        }
        $config_array = array();
        foreach ($array as $key => $value) {
        	if(is_array($value)){
        		foreach ($value as $k=> $v) {
        			$config_array["config['" . $key . "']['".$k."']"] = $v;
				}
        	}else{
        		$config_array["config['" . $key . "']"] = $value;
        	}
        }
        $config_base_files=glob(ROOT_PATH.'inc/base/*.ini.php');
        $config_site_files=glob(ROOT_PATH.'inc/site/'.DEFAULT_SITE.'/*.ini.php');
        $config_files=array_merge((array)$config_base_files,(array)$config_site_files);
        if(!empty($config_files)){
        	foreach ($config_files as $config_file) {
        		$config = file_get_contents($config_file); //读取配置
		        foreach ($config_array as $name => $value) {
		            $name = str_replace(array("'", '"', '[','*'), array("\\'", '\"', '\[','\*'), $name); //转义特殊字符，再传给正则替换
		            if (is_string($value) && !in_array($value, array('true', 'false', '3306'))) {
		                if(!is_numeric($value)){
		                    $value = "'" . $value . "'"; //如果是字符串，加上单引号
		                }
		            }
		            $config = preg_replace("/(\\$" . $name . ")\s*=\s*(.*?);/iU", "$1={$value};", $config); //查找替换
		        }
				// 写入配置
		        if (!@file_put_contents($config_file, $config)){
		           return false;
		        }
        	}
        }
        return true;
    }

	//获取模板内容
    public function tpl_list()
    {
        $tpl_dir=realpath(ROOT_PATH.'themes/'.config('TPL_TEMPLATE_NAME'));
        if(!is_dir($tpl_dir)){
        	return false;
        }
        $list_file=scandir($tpl_dir);
        if(is_array($list_file)){
        	$list=array();
	        foreach ($list_file as $value) {
	            if ($value != "." && $value != "..") {
	                $list[]=$value;
	            }
	        }
        }
        return $list;
    }

    //获取模板路径
    public function themes_list()
    {
        $tpl_dir=realpath(ROOT_PATH.config('TPL_TEMPLATE_PATH'));
        if(!is_dir($tpl_dir)){
        	return false;
        }
        $list_file=scandir($tpl_dir);
        if(is_array($list_file)){
        $list=array();
	        foreach ($list_file as $value) {
	            if ($value != "." && $value != ".."&&!strpos($value,".")) {
	                $list[]=$value;
	            }
	        }
        }
        return $list;
    }


}